Data Mapping
Changing data before sending it to server
We often encounter the need to map
data before sending data to server. This is usually required for two reasons.
One of them is breaking changes to the server api
, which may require many updates to our existing code, which may be
dangerous for the application and introduce regression.
Another case is sending FormData
, which is impossible to represent in the form of an exact interface in terms of the
fields it contains. In order not to send something that is equivalent to the type any
, we can specify the correct type
in the command and then map everything to FormData just before it gets added to
Dispatcher.
This way, we ensure very type-safe
and flexible
development of our application.
Set payload data mapper
Below example show the implementation for FormData
export const postUserProfile = builder
.createCommand<boolean, UserProfile>()({
method: "PATCH",
endpoint: "/users/profile/:userId",
})
.setDataMapper((data) => {
// Transform data:UserProfile into FormData
const formData = new FormData();
Object.entries(([key, value]) => {
formData.append(key, value);
});
// Return new data format
return formData;
});